<template>
  <div>
     <n-card content-style="padding: 0;">
        <n-tabs
          @close="handleClose"
            type="card"
            size="large"
            :tabs-padding="20"
            pane-style="padding: 20px;"
            closable
            v-model:value="activeName" 
            @update:value="handleUpdateValue"
        >
       
        <n-tab-pane  :name="tag.name" :tab="tag.tag" v-for="(tag,tagIndex) in tagOptions" :key="tagIndex">
            <div v-if="activeName == 'all'">
              <div style="display: flex;gap: 20px;">
                <n-button type="success" @click="openPop">
                  分配插件
                </n-button>
                <n-input-group>
                  <n-select
                  v-model:value="otherValue"
                    :style="{ width: '260px' }" 
                    filterable 
                    placeholder="请选择用户"
                    :options="userOptions"
                    clearable
                  />
                <n-button @click="findUser" type="primary" ghost>
                  查看插件
                </n-button>
              </n-input-group>
              </div>
              <div v-if="data.length" class="boxBg">
                  <div class="boxMessage" v-for="(item,index) in data" :key="index">
                      <n-card style="height: 120px;" :title="item.title" hoverable>
                          <div style="display: flex; justify-content: space-between;">
                              <div>
                                  {{item.plugsDescribe}}
                              </div>
                              <div>
                                  <n-image
                                      width="40"
                                      :src="Https()+item.image"
                                  />
                              </div>
                              </div>
                      </n-card>
                  </div>
              </div>
              <n-empty v-else description="你看你就是没充钱">
                  <template #extra>
                      <n-button size="small">
                          充点小钱
                      </n-button>
                  </template>
              </n-empty>
            </div>
            <div v-else-if="activeName == 'my'">
                <div v-if="data.length" class="boxBg">
                  <div @click="goTo(item,'my')" class="boxMessage" v-for="(item,index) in data" :key="index">
                      <n-card style="height: 120px;" :title="item.title" hoverable>
                          <div style="display: flex; justify-content: space-between;">
                              <div>
                                  {{item.plugsDescribe}}
                              </div>
                              <div>
                                  <n-image
                                      width="40"
                                      :src="Https() + item.image"
                                  />
                              </div>
                              </div>
                      </n-card>
                  </div>
              </div>
              <n-empty v-else description="你看你就是没充钱">
                  <template #extra>
                      <n-button size="small">
                          充点小钱
                      </n-button>
                  </template>
              </n-empty>
            </div>

            <div v-else>
                <div v-if="otherUserOptions.length" class="boxBg">
                  <div @click="goTo(item,'other')" class="boxMessage" v-for="(item,index) in otherUserOptions" :key="index">
                      <n-card style="height: 120px;" :title="item.title" hoverable>
                          <div style="display: flex; justify-content: space-between;">
                              <div>
                                  {{item.plugsDescribe}}
                              </div>
                              <div>
                                  <n-image
                                      width="40"
                                      :src="Https() + item.image"
                                  />
                              </div>
                              </div>
                      </n-card>
                  </div>
              </div>
              <n-empty v-else description="你看你就是没充钱">
                  <template #extra>
                      <n-button size="small">
                          充点小钱
                      </n-button>
                  </template>
              </n-empty>
            </div>
            
        </n-tab-pane>
         
        </n-tabs>
    </n-card>

   <yingModal  :title="'分配插件'" @close="cancelCallback" @confirm="submitCallback" :SkuShow="showModal" >
      <template #content>
         <div style="display: flex;gap: 20px 0;flex-direction: column;">
        <div style="margin-top: 10px;">
            <n-select
                v-model:value="selectedArray"
                multiple
                filterable 
                placeholder="请选择用户"
                :options="userOptions"
                clearable
                />
        </div>
        <div>
            <n-transfer
             style="height:500px"
                v-model:value="value"
                :options="options"
                :render-target-label="renderLabel"
            />  
        </div>
      </div>
      </template>
  </yingModal>
   
   
  </div>
</template>

<script setup lang="ts">
import yingModal from "@/components/common/YingModal.vue"
import { NAvatar, NButton, NImage, NSwitch, NTag  } from 'naive-ui'
import type { FormInst } from 'naive-ui'
import { nextTick, onMounted, ref } from 'vue'
import { useUserStore } from '@/store'
import api from './api'
import { Https,setPagination } from "@/utils"
import { forEach } from 'lodash-es'
const router = useRouter()
const userStore = useUserStore()
const activeName = ref('all')
const showModal = ref(false)
const value = ref([])
const selectedArray = ref([])
const userOptions = ref([])
const otherUserOptions = ref([])
const otherValue = ref([])
const tagOptions = ref([
  {
    name:'all',
    tag:'全部插件',
  },
  {
    name:'my',
    tag:'我的插件',
  }
])

onMounted(() => {
  List()
  userList()
  console.log(userStore.userInfo)
//   myPluin()
})

const options = ref([])

const renderLabel: TransferRenderTargetLabel = function ({ option }) {
    return h(
    'div',
    {
        style: {
        display: 'flex',
        margin: '6px 0'
        }
    },
    {
        default: () => [
        h(NAvatar, {
            round: true,
            src: option.image as string,
            size: 'small',
            fallbackSrc:
            'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg'
        }),
        h(
            'div',
            {
            style: {
                display: 'flex',
                marginLeft: '6px',
                alignSelf: 'center'
            }
            },
            { default: () => option.label }
        )
        ]
    }
    )
}

const params = ref({
  pageNum: 1,
  pageSize: 200,
  keyword: '',
  plugin_id:'all'
})
const data = ref([])

async function List() {
  try {
    const res: any = await api.ListApi(params.value)
    if (res.code == 200) {
        data.value = res.data.list
        options.value = res.data.list.map(item =>{
            return {
                label:item.title,
                image:item.image,
                value:item.plugin_id
            }
        });

    }
  }
  catch (error) {
    console.error(error)
  }
}

async function setMyPluin() {
  try {
    const res: any = await api.myPluinApi(params.value)
    if (res.code == 200) {
      value.value = res.data.list.map(item => {return item.plugin_id});
    }
  }
  catch (error) {
    console.error(error)
  }
}
const userData = ref([]);
async function userList() {
  try {
    const res: any = await api.userListApi({
        pageNum: 1,
        pageSize: 200,
        keyword: '',
    })
    if (res.code == 200) {
        userOptions.value = res.data.pageData.map(item =>{
            return {
                label:item.account,
                value:item.user_id
            }
        });
    }
  }
  catch (error) {
    console.error(error)
  }
}
async function myPluin() {
  try {
    const res: any = await api.myPluinApi(params.value)
    if (res.code == 200) {
      data.value = res.data.list
      value.value = res.data.list.map(item => {return item.plugin_id});
    }
  }
  catch (error) {
    console.error(error)
  }
}


const handleUpdateValue = (name, info) => {
    console.log(name,info)
    if(activeName.value == 'all'){
        activeName.value = 'all';
        data.value = []
        List();
    }else if(activeName.value == 'my'){
        activeName.value = 'my';
        data.value = []
        myPluin();
    }else{
      activeName.value = name;
      otherValue.value = name;
      findUser();
      
    }
    
};

function openPop(){
    setMyPluin();
    showModal.value = true;
}



async function submitCallback() {
    if(selectedArray.value.length == 0){
      $message.error('请选择用户!')
      showModal.value = true;
      return
    }
    var strIds = ''
    value.value.forEach((item,index)=>{
        if(index == 0){
            strIds += item;
        }else{
            strIds += `,${item}`
        }
    })
    const res = await api.userPluginApi({
        plugin_ids:strIds,
        users_ids:selectedArray.value
    })
    if(res.code == 200){
     
        selectedArray.value = []
        $message.success('分配成功!')
    }
}
function cancelCallback() {
  
//   categoryList();
  showModal.value = false
}
const otherValueNew = ref('')
async function findUser() {
 
  var newData = {}
  userOptions.value.forEach(item=>{
    if(otherValue.value == item.value){
      newData = {
        user_id:item.value,
        account:item.label,
        
      }
    }
  })
 
  otherValueNew.value = newData
  if(newData){
    const res = await api.otherUserPluginApi({
      user_id:newData.user_id
    });
    if(res.code == 200){
      tagOptions.value.push({
        name:newData.user_id,
        tag:newData.account,
      })
      otherUserOptions.value = res.data.list
      const a = tagOptions.value.map(item => {
          return item.name
      })
      tagOptions.value = tagOptions.value.filter((item, index) => {
          return a.indexOf(item.name) === index
      })
    }
  }else{
    $message.error('请先选择用户')
  }
  
}
function handleClose(itemTag){
 
  if(itemTag == 'all' || itemTag == 'my'){
    $message.error('不能删除该tag')
    return
  }

  tagOptions.value = tagOptions.value.filter((item, index) => item.name !== itemTag);
  
}

function goTo(item,type){
 
  if(type == 'my')
    item.user_id = userStore.userInfo.user_id
  else
    item.user_id = otherValueNew.value.user_id
  if(item.status)
    router.push({
      path:item.paths,
      query:item
    })
  else
    $message.error('插件被禁用!')    
   
}

</script>

<style>
    .boxBg{
        display: grid;
        /* grid-template-columns: repeat(5, 1fr);    */
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        /* grid-auto-rows: 200px; */
        gap: 20px;
        margin: 20px 0;
    
        
    }
    
</style>